<template>
	<view>
		<view class="flex-j-a content" v-for="(item, index) in userList" :key="index">
			<view class="">
				<text>{{ item.name }}</text>
				<image :src="item.avatar" mode="" style="width: 50px;height: 50px;"></image>
			</view>
			<view class="flex-a-c">
				<button type="warn" @click="updateUserById(item)">修改</button>
				<button style="margin: 0 5px;" type="default" @click="deleteUserById(item._id)">删除</button>
				<button type="default" @click="uploadAvatarById(item._id)">上传头像</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				userList: []
			}
		},
		onLoad() {
			this.getUserList()
		},
		methods: {
			async getUserList() {
				const {result: res} = await uniCloud.callFunction({
					name:'get_user_list'
				})
				console.log(res);
				this.userList = res.data.data
			},
			async deleteUserById(id) {
				console.log(id);
				const res = await uniCloud.callFunction({
					name: 'del_user',
					data: {
						id
					}
				})
				console.log(res);
				this.getUserList()
			},
			uploadAvatarById(_id) {
				uniCloud.chooseAndUploadFile({
					success: res => {
						const filename = res.tempFilePaths[0].split('/')[res.tempFilePaths[0].split('/').length -1]	
						uniCloud.uploadFile({
							filePath: res.tempFilePaths[0],
							cloudPath: filename,
							success: async res => {
								if (res.fileID) {
									const res = await uniCloud.callFunction({
										name:'update_user',
										data: {
											_id,
											avatar: res.fileID
										}
									})
									this.getUserList()
								}
							}
						})
					}
				})
			}
		}
	}
</script>

<style scoped lang="scss">
.content {
	padding: 5px 10px;
}
.flex-a-c {
	display: flex;
	align-items: center;
}
.flex-j-a {
	display: flex;
	align-items: center;
	justify-content: space-between;
}
</style>
